<?php

namespace App\Http\Controllers\API;

use App\Http\Resources\ExhibitorInformationResource;
use App\Models\ExhibitorInformation;
use App\Models\ExhibitorMessage;
use App\Models\ExhibitorUser;
use App\Services\AliSmsService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ExhibitorInformationController extends Controller
{
    public function mobileSmsLogin(Request $request)
    {
        $input = $request->all();
        $mobile = $input['phone'];
        $code = $input['code'];
        if (!$mobile) {
            return $this->failure('手机号不能为空');
        }
        $exhibitor_information = ExhibitorInformation::query()->where('phone', $mobile)->first();

        if (!$exhibitor_information) {
            return $this->failure("用户{$mobile}不存在");
        }
        if ($exhibitor_information->status == 0) {
            return $this->failure('用户被禁用');
        }
        if (!$code) {
            return $this->failure('验证码不能为空');
        }

        if (!AliSmsService::validate($request->get('code'), $request->get('phone'))) {
            return $this->failure('验证码错误');
        }

        return $this->success($this->createTokenUser($exhibitor_information));
    }

    public function mobilePWDLogin(Request $request)
    {
        $input = $request->all();
        $name = $input['name'];
        $pwd = $input['pwd'];
        if (!$name) {
            return $this->failure('请输入公司全称');
        }
        $exhibitor_information = ExhibitorInformation::query()->where('name', $name)->first();

        if (!$exhibitor_information) {
            return $this->failure("用户{$name}不存在");
        }
        if ($exhibitor_information->status == 0) {
            return $this->failure('用户被禁用');
        }
        if (!$pwd) {
            return $this->failure('密码不能为空');
        }
        if (empty($name) || !Hash::check($pwd, $exhibitor_information->password)) {
            return $this->failure('账号或密码错误');
        }
        session()->put('exhibitor_information_id', $exhibitor_information->id);
//        $exhibitor_message = ExhibitorMessage::query()->where('status', 1)->first();
//
        session()->put('exhibitor_message_id', 1);

        return $this->success($this->createTokenUser($exhibitor_information));
    }

    protected function createTokenUser(ExhibitorInformation $exhibitor_information)
    {
        $success = (new ExhibitorInformationResource($exhibitor_information))->toArray(request());
        $success['token_type'] = 'Bearer';
        $success['token'] = $exhibitor_information->createToken('ExhibitorInformation')->accessToken;

        return $success;
    }


}
